<%-- 
    Document   : hotItemScanner
    Created on : Apr 5, 2013, 1:35:01 PM
    Author     : asikprad
--%>

<%@tag description="put the tag description here" pageEncoding="windows-1252"%>
<%@ attribute name="xmlContentId" required="true"
              description="Id for the xml content to scan for hot items."%>

<%@ attribute name="branchId" required="true"
              description="Id for the current branch."%>

<script language="Javascript" type="text/javascript">
    var hotItem = new Object();
    hotItem.logToConsole = function(message) {
        console.log(message);
    };
    hotItem.addMessage = function(message) {
        $('#hot-terms-message').empty().append(message);
    };
    hotItem.alertMessage = function(message) {
        alert(message);
    };
    hotItem.getDitaContainerValue = function() {
        return $("textarea[id='${xmlContentId}']").val();
    };
    hotItem.setDitaContainerValue = function(ditaVal) {
        $("textarea[id='${xmlContentId}']").val(ditaVal);
    };
    hotItem.error = function() {
        alert("error");
    };
    hotItem.showPreview = function(preview) {
        $("#hotItem-preview").empty().append(this.decode(preview));
    };
    hotItem.updateDitaContainer = function(currentTopicBody) {
        var ditaVal = this.encodedTopic.replace(
                new RegExp("<body>(.+?)</body>"), "<body>    "
                + currentTopicBody + "</body>");
        this.setDitaContainerValue(this.decode(ditaVal));
    };
    hotItem.heatTopicBody = function(currentBody, item) {
        return currentBody.replace(new RegExp(item['term'], "i"),
                '<term keyref="' + item['reference'] + '">' + item['term']
                + '</term>');
    };
    hotItem.heatPreview = function(currentBody, item) {
        return currentBody.replace(new RegExp(item['term'], "i"), '<term>'
                + item['term'] + '</term>');
    };
    hotItem.unheatBody = function(currentBody) {
        return currentBody.replace(/<term.*?>/ig, '').replace(/<\/term>/g, '');
    };

    hotItem.encode = function(s) {
        return String(s).replace(/[\n]/g, "~");
    };
    hotItem.decode = function(s) {
        return String(s).replace(/[~]/g, "\n");
    };
   
    hotItem.currentM = 0;
    hotItem.heat = function() {
        hotItem.permanentPreview = hotItem.currentPreview();
        hotItem.logToConsole("found: " + hotItem.foundTerm);
        hotItem.removeTerm(hotItem.foundTerm);
        hotItem.currentM--;
    };
    hotItem.findPrev = function() {
        var str = hotItem.permanentPreview;
        var replaceStr = hotItem.replaceIndex(str, hotItem.currentM - 1);
        if (str === replaceStr) {
            hotItem.addMessage("beginning of search");
        } else {
            hotItem.updatePreview(replaceStr);
        }
    };
    hotItem.findNext = function() {
        var str = hotItem.permanentPreview;
        var replaceStr = hotItem.replaceIndex(str, hotItem.currentM + 1);
        hotItem.logToConsole(hotItem.createRegex());
        if (str === replaceStr) {
            hotItem.currentM = 0;
        } else {
            hotItem.updatePreview(replaceStr);
        }
    };
    hotItem.regexTerm = function(term) {
        return '(' + term + '(?!<\/term>))';
    };
    hotItem.removeTerm = function(term) {
        var index = hotItem.regexTerms.indexOf(term);
        if (index > -1) {
            hotItem.regexTerms.splice(index, 1);
        }
    };
    hotItem.addTerm = function(term) {
        var index = hotItem.regexTerms.indexOf(term);
        if (index < 0) {
            hotItem.regexTerms.push(term);
        }
    };
    hotItem.createRegex = function() {
        var regex = "";
        for (var i = 0; i < hotItem.regexTerms.length; i++) {
            if (i !== hotItem.regexTerms.length - 1) {
                regex += hotItem.regexTerm(hotItem.regexTerms[i]) + '|';
            } else {
                regex += hotItem.regexTerm(hotItem.regexTerms[i]);
            }
        }
        return  regex;
    };
    hotItem.createTermTag = function(term) {
        if (hotItem.heatedMap[term.toLowerCase()] !== undefined) {
            return "<term keyref='" + hotItem.heatedMap[term.toLowerCase()]['reference'] + "'>" + term + "</term>";
        }
    };
    hotItem.replaceIndex = function(body, n) {
        m = 0;
        return body.replace(new RegExp(hotItem.createRegex(), "ig"), function(x) {
            m++;
            if (n === m) {
                hotItem.currentM = m;
                hotItem.foundTerm = hotItem.createTermTag(x);
                hotItem.logToConsole(x + " : " + hotItem.foundTerm);
                return hotItem.foundTerm;
            } else {
                return x;
            }
        });
    };
    hotItem.startOver = function() {
        hotItem.permanentPreview = hotItem.originalPreview;
        hotItem.currentM = 0;
        $('#hot-terms input:checked').each(function() {
            hotItem.addTerm($(this).attr('id'));
        });
        hotItem.updatePreview(hotItem.originalPreview);
    };
    hotItem.setCurrentPreview = function(body) {
        $('#hotItem-preview').empty().append(this.decode(body));       
    };
    hotItem.currentPreview = function() {
        return $('#hotItem-preview').html();
    };
    hotItem.updatePreview = function(body) {
        $('#hotItem-preview').empty().append(this.decode(body));
        hotItem.updateDitaContainer(body);
    };
    hotItem.addCheckbox = function(item) {
        var container = $('#hot-terms');
        var html = '<input type="checkbox" id="' + item.term + '" value="'
                + item.term + '"checked /> <label for="' + item.term + '">'
                + item.term + '</label><br/>';
        container.append($(html));
    };
    hotItem.unchecked = function(term) {
        hotItem.permanentPreview = hotItem.currentPreview().replace(new RegExp('<term.*>' + term + '</term>', "ig"), "CAS");
        hotItem.updatePreview(hotItem.permanentPreview);
        hotItem.removeTerm(term);
        hotItem.currentM = 0;
    };
    hotItem.startScan = function() {
        this.topic = this.getDitaContainerValue();
        $("#hotItem-start").attr('disabled','disabled');
        $("#hotItem-heat").removeAttr("disabled");
        $("#hotItem-find-next").removeAttr("disabled");
        $("#hotItem-start-over").removeAttr("disabled");
        
        if (this.topic !== null && this.topic !== "") {
            //this.body = new RegExp("<body>(.+?)</body>").exec(this.topic)[1];
            this.encodedTopic = this.encode(this.topic);
            this.encodedBody = new RegExp("<body>(.+?)</body>").exec(this.encodedTopic)[1];
            this.setCurrentPreview(this.encodedBody);
        }
        hotItem.permanentPreview = hotItem.currentPreview();
        hotItem.originalPreview = hotItem.currentPreview();
        $.ajax({
            url: "scan",
            type: "GET",
            dataType: 'json',
            success: function(data) {
                $('#hot-terms').empty();
                hotItem.heatedMap = new Array();
                hotItem.regexTerms = new Array();
                $.map(data, function(value) {
                    hotItem.heatedMap[value.term.toLowerCase()] = value;
                    hotItem.addMessage("");
                    hotItem.addCheckbox(value);
                    hotItem.regexTerms.push(value.term);
                });
            }});
        $('#hot-terms').bind("change", function() {
            $('#hot-terms input:not(:checked)').each(function() {
                hotItem.unchecked($(this).attr('id'));
            });
            $('#hot-terms input:checked').each(function() {
                hotItem.addTerm($(this).attr('id'));
            });
        });
    };
</script>
<table>
    <tr>
        <td class="tab-subhead">Hot Terms</td>
        <td class="tab-subhead"><div id="hot-terms-message"></div></td>
    </tr>
    <tr>
        <td valign="top">            
            <div id="hot-terms"></div>
        </td>
        <td valign="top">

            <div id="hotItem-preview">
                <!--This is where the preview goes-->
            </div>
        </td>
    </tr>
</table>
<div class="buttons">    
    <input type="submit" onclick="hotItem.startScan();
            return false;" name="start" value="start" id="hotItem-start"/>
    <input type="submit" onclick="hotItem.heat();
        return false;" name="heat" value="heat" disabled="disable" id="hotItem-heat"/>
    <input type="submit" onclick="hotItem.findNext();
        return false;" name="next" value="next" disabled="disable" id="hotItem-find-next"/>
    <input type="submit" onclick="hotItem.startOver();
        return false;" name="startOver" value="start over?" disabled="disable" id="hotItem-start-over"/>
</div>